﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
//using StockMonitor.Helper;

using System.Threading;
//using StockMonitor.Business;
//using StockMonitor.Configuration;
using Tigera.T_Definition;
using Tigera.LibCodeUtils;


namespace StockMonitor.UserControls
{

    public partial class UCAccountInfo : UserControl//MdiUserControl
    {

        #region Ctor.


        public UCAccountInfo()
            : base()
        {

            DialogResult ret = FormLogin.Login();
            InitializeComponent();
            this.DataBindings.Add("Enabled", AuthUserService.Instance, "Logined", false, DataSourceUpdateMode.OnPropertyChanged);
            AuthUserService.Instance.OnBasicACCountInfoRec += new EventHandler(Instance_OnBasicACCountInfoRec);
            if (ret == DialogResult.OK)
            {
                Onload();
            }



        }


        public string Title
        {
            get
            {
                return "账户信息";
            }

        }

        void Instance_OnBasicACCountInfoRec(object sender, EventArgs e)
        {
            OnUpdateUIthis(sender, e);
        }


        #endregion




        #region EventHandler






        /// <summary>
        /// Handles the Tick event of the timerUpdateUI control.
        /// 1. 刷新余额
        /// 2. 刷新累计成交
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:38 PM</datetime>
        /// </remarks>
        private void timerUpdateUI_Tick(object sender, EventArgs e)
        {
            Onload();

            AutoSellAllPostions();
        }




        /// <summary>
        /// Handles the Click event of the btnRefresh control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:37 PM</datetime>
        /// </remarks>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Onload();
        }

        #endregion

        #region MdiUserControl Members

        /// <summary>
        /// 窗体加载.
        /// 刷新今日成交记录。
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:40 PM</datetime>
        /// </remarks>
        public void Onload()
        {
           
            AuthUserService.Instance.QueryUserInfo();
            AppMgr.Instance.Mqclient.OnList_403 -= Mqclient_OnList_403;
            AppMgr.Instance.Mqclient.OnList_403 += new EventHandler<Tigera.LibCommon.TiEventArgs<List<ResultF403>>>(Mqclient_OnList_403);

            AuthUserService.Instance.NetGetPosInfo();




            QueryServerRimStatus();


            

        }

        private void QueryServerRimStatus()
        {
            AppMgr.Instance.Mqclient.OnResponseTadeRiskGloStateQuery -= Mqclient_OnResponseTadeRiskGloStateQuery;
            AppMgr.Instance.Mqclient.OnResponseTadeRiskGloStateQuery += new EventHandler<Tigera.LibCommon.TiEventArgs<ResponseTadeRiskGloStateQuery>>(Mqclient_OnResponseTadeRiskGloStateQuery);


            TradeCMD cmd = new TradeCMD();
            cmd.Ope = TradeRiskOpe.TadeRiskGloStateQuery;
            AppMgr.Instance.Mqclient.SendDataTo(AppMgr.TradeRiskExName, ESHelper.Pack(ref cmd));
        }

        void Mqclient_OnResponseTadeRiskGloStateQuery(object sender, Tigera.LibCommon.TiEventArgs<ResponseTadeRiskGloStateQuery> e)
        {
            if (this.InvokeRequired)
            {
                //this.inv

                this.Invoke(

                    new Action(() =>
                                 {
                                     this.dataGridView_state.Rows.Clear();

                                     this.dataGridView_state.Rows.Add("全局风控", e.Data.OnRunning ? "交易进行中" : "禁止交易");
                                 }
                               )
                           );
            }
            else
            {
                this.dataGridView_state.Rows.Clear();

                this.dataGridView_state.Rows.Add("全局风控", e.Data.OnRunning ? "交易进行中" : "禁止交易");
            }
        }

        void Mqclient_OnList_403(object sender, Tigera.LibCommon.TiEventArgs<List<ResultF403>> e)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => this.dgvPostions.DataSource = e.Data));


                }
                else
                {
                    this.dgvPostions.DataSource = e.Data;
                }
            }
            catch (System.Exception ex)
            {

            }

        }

        private void OnUpdateUIthis(object sender, EventArgs e)
        {
            this.lbUserAccount.Text = AuthUserService.Instance.FundAccount;
            this.lbUserName.Text = AuthUserService.Instance.ClientName;

            AuthUserService[] info = { AuthUserService.Instance };
            this.dgvAccountInfo.AutoGenerateColumns = false;
            this.dgvAccountInfo.DataSource = info;

            this.dgvPostions.AutoGenerateColumns = true;



        }

        /// <summary>


        #endregion




        private void dgvSell_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= this.dgvPostions.RowCount)
            {
                return;
            }
            string val = this.dgvPostions.Rows[e.RowIndex].Cells[3].Value.ToString();


            int intval = int.Parse(val);
            if (intval == 0)
            {
                return;
            }

            FormClearPos form = new FormClearPos();
            form.Stockcode = this.dgvPostions.Rows[e.RowIndex].Cells[0].Value as string;
            form.Amount = intval;
            DialogResult res = form.ShowDialog(this);
            if (res == DialogResult.OK)
            {
                this.btnRefresh_Click(this, EventArgs.Empty);
            }

        }

        void AutoSellAllPostions()
        {
            if (ClientTradeRisk.Instance.UintNetValueRiskControlEnable && ClientTradeRisk.Instance.Price < AuthUserService.Instance.NetUnitValue)
            {
                var count = this.dgvPostions.RowCount;
                for (int i = 0; i < count; ++i)
                {
                    string val = this.dgvPostions.Rows[i].Cells[3].Value.ToString();
                    int amount = int.Parse(val);
                    if (amount == 0)
                    {
                        continue;
                    }
                    var Stockcode = this.dgvPostions.Rows[i].Cells[0].Value as string;
                    TradeCMD cmd = new TradeCMD();
                    cmd.Target = Stockcode;
                    cmd.Ope = TradeRiskOpe.TradeClearPos;

                    cmd.Price = float.Parse(this.dgvPostions.Rows[i].Cells[4].Value.ToString());
                    cmd.Amount = amount;
                    AppMgr.Instance.Mqclient.SendDataTo(AppMgr.TradeRiskExName, ESHelper.Pack(ref cmd));

                }
            }

        }

        private void cbAutoRefresh_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbAutoRefresh.Checked)
            {
                try
                {
                    int val = int.Parse(this.textBoxTimer.Text);
                    if (val < 5)
                    {
                        MessageBox.Show("刷新时间太短了");
                        return;
                    }
                    this.timerUpdateUI.Interval = val * 1000;
                    this.timerUpdateUI.Enabled = true;
                }
                catch (System.Exception ex)
                {
                    return;
                }
            }
            else
            {
                this.timerUpdateUI.Enabled = false;
            }
        }

        private void btn_AutoRiskSetting_Click(object sender, EventArgs e)
        {
            FormRiskSetting form = new FormRiskSetting();


            if (form.ShowDialog(this) == DialogResult.OK)
            {
                this.textBoxTimer.Text = 10.ToString();
                this.cbAutoRefresh.Checked = true;
                this.timerUpdateUI.Enabled = true;
                this.textBoxTimer.Enabled = false;
                this.cbAutoRefresh.Enabled = false;
            }
            else
            {
                this.textBoxTimer.Enabled = true;
                this.cbAutoRefresh.Enabled = true;
            }
        }

        private void btn_ResumeTrade_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "是否启动服务器自动交易?", "警告", MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;

            TradeCMD cmd = new TradeCMD();
            cmd.Ope = TradeRiskOpe.TradeRiskGloStart;
            AppMgr.Instance.Mqclient.SendCMD(cmd);

            QueryServerRimStatus();
        }

        private void btn_StopGloTrade_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "是否停止服务器自动交易?", "警告", MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;

            TradeCMD cmd = new TradeCMD();
            cmd.Ope = TradeRiskOpe.TradeRiskGloStop;
            AppMgr.Instance.Mqclient.SendCMD(cmd);

            QueryServerRimStatus();
        }
    }
}
